package com.jams.goodox.activity.serve.park;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.hangzhou.jin.customview.TextMoreLayout;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.serve.meet.MeetPartOrderSureActivity;
import com.jams.goodox.constant.Constants;
import com.jams.goodox.entity.CarPlaceInfo;
import com.jams.goodox.entity.ParkingBean;
import com.jams.goodox.entity.resp.ParkPlaceOrderResp;
import com.jams.goodox.entity.resp.ParkingResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.UserUtils;
import com.jams.goodox.utils.Utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 停车申请
 * <p>
 * create by 顾佳佳 on 2017/05/23
 */
public class ParkingApplyActivity extends BaseActivity implements ParkTimeDialog.OnChooseDate {

    @Bind(R.id.et_parking)
    EditText etParking;
    @Bind(R.id.tv_parking_underground)
    TextView tvParkingUnderground;
    @Bind(R.id.tv_parking_ground)
    TextView tvParkingGround;
    @Bind(R.id.tv_parking_first_money)
    TextView tvParkingFirstMoney;
    @Bind(R.id.tv_parking_second_money)
    TextView tvParkingSecondMoney;
    @Bind(R.id.tv_parking_count)
    TextView tvParkingCount;
    @Bind(R.id.tml_parking_end)
    TextMoreLayout tmlParkingEnd;
    @Bind(R.id.tv_month_hint)
    TextView tvMonthHint;
    @Bind(R.id.relative_no_data)
    RelativeLayout noDataRelative;
    @Bind(R.id.tx_start_time)
    TextView txStartTime;
    @Bind(R.id.relative_start_time)
    RelativeLayout relative_start_time;
    @Bind(R.id.linear_car_apply)
    LinearLayout linear_car_apply;

    private String carType ;//车位类型 0：地下 1：地上
    private int combo = -1;//套餐选择 1：包月 2：包年

    private String subId;
    private String busId;
    private boolean isPersonPark;

    public static final String Type_Car_Station_Down="0";//地下车位
    public static final String Type_Car_Station_Up="1";//地面车位

    public static final int Type_Menu_Month=2;//月
    public static final int Type_Menu_Year=3;//年

    private ParkingResp.DataBean.DataMapBean dataMapBean;//返回的数据
    private List<ParkingBean> chooseParkingList;//选择的地面or地下列表

    private int firstMenuType;//选中的第一个套餐类型
    private long curDateLong;//后台返回当前时间戳

    private String chooseId;//选中的id
    private String endTime;//结束时间

    private int position;//时间滚轮的位置
    private String orderId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_parking_apply;
    }

    @Override
    protected void init() {
        setBarTitle(false);
        Utils.editInputToLarge(etParking);
        subId=getIntent().getStringExtra("subId");
        busId=getIntent().getStringExtra("busId");
        isPersonPark=getIntent().getBooleanExtra("isPersonPark",false);
        getData();
    }

    private void getData(){
        showLoading();
        Map<String,Object> params=new HashMap<>();
        params.put("enterpriseId", DataCacheManager.getInstance().getUser().getEnterpriseId());
        params.put("identity",isPersonPark?0:1);
        params.put("pubobj", UserUtils.isUnLinkCompany()?0:1);
        if(!TextUtils.isEmpty(orderId)) params.put("orderId",orderId);
        enqueue(createCallService(ServiceService.class).getcarPlaceList(params), new RetrofitCallbackListener<ParkingResp>() {
            @Override
            public void onSuccess(Call<ParkingResp> call, ParkingResp result) {
                misLoading();
                linear_car_apply.setVisibility(View.VISIBLE);
                noDataRelative.setVisibility(View.GONE);
                if(result.getData()==null||result.getData().getDataMap()==null){
                    noDataRelative.setVisibility(View.VISIBLE);
                    return;
                }
                curDateLong=result.getData().getStartTime();
                dataMapBean=result.getData().getDataMap();
                if(!TextUtils.isEmpty(result.getData().getCurNumber()))etParking.setText(result.getData().getCurNumber());//续约返回车牌号，直接放置在界面中
                if(dataMapBean.getPublist()==null||dataMapBean.getPublist().size()==0){
                    noDataRelative.setVisibility(View.VISIBLE);
                    return;
                }
                initData();
            }

            @Override
            public void onError(String msg) {
                misLoading();
                noDataRelative.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 获取到数据后，初始化车位信息
     * 1：存在地面显示地面，存在地下显示地下
     * 2：在地下存在时默认选择地下，仅当只有地上时选择地上
     */
    private void initData(){
        for(ParkingBean parkingBean:dataMapBean.getPublist()){//遍历，如果存在地面显示地面，如果存在地下，显示地下
            if(parkingBean.getPlaceType().equalsIgnoreCase(Type_Car_Station_Down)){
                tvParkingUnderground.setVisibility(View.VISIBLE);
                carType=Type_Car_Station_Down;
            }
            if(parkingBean.getPlaceType().equalsIgnoreCase(Type_Car_Station_Up)){
                tvParkingGround.setVisibility(View.VISIBLE);
                if(TextUtils.isEmpty(carType))carType=Type_Car_Station_Up;//仅当无地下支付类型，对应选择的cartype是地上
            }
        }
        if(!TextUtils.isEmpty(carType))setCarType(carType);
    }

    /**
     * 每次初始化or切换车位类型，执行以下方法，用于修改选中颜色，字体颜色，并初始化套餐选择
     * @param type Type_Car_Station_Down="0";//地下车位 Type_Car_Station_Up="1";//地面车位
     */
    private void setCarType(String type) {
        if(carType==null)return;
        this.carType = type;
        switch (carType) {
            case Type_Car_Station_Down://地下
                tvParkingUnderground.setTextColor(ContextCompat.getColor(this, R.color.font_main));
                tvParkingUnderground.setBackgroundResource(R.drawable.red_submit_btn_bg);
                tvParkingGround.setTextColor(ContextCompat.getColor(this, R.color.font_hint));
                tvParkingGround.setBackgroundResource(R.drawable.gray_stroke_bg);
                break;
            case Type_Car_Station_Up://地上
                tvParkingGround.setTextColor(ContextCompat.getColor(this, R.color.font_main));
                tvParkingGround.setBackgroundResource(R.drawable.red_submit_btn_bg);
                tvParkingUnderground.setTextColor(ContextCompat.getColor(this, R.color.font_hint));
                tvParkingUnderground.setBackgroundResource(R.drawable.gray_stroke_bg);
                break;
        }
        initCombo();
    }

    /**
     * 每次切换地面地下，初始化套餐ui,并默认选择第一个
     * 此处注意：包月or包年谁排于第一位由后台返回
     */
    private void initCombo(){
        if(TextUtils.isEmpty(carType))return;
        switch (carType){
            case Type_Car_Station_Down:
                chooseParkingList=dataMapBean.getDownlist();
                break;
            case Type_Car_Station_Up:
                chooseParkingList=dataMapBean.getUplist();
                break;
        }
        if(chooseParkingList==null||chooseParkingList.size()==0)return;
        tvParkingFirstMoney.setVisibility(View.VISIBLE);
        if(chooseParkingList.get(0).getMenuType()==Type_Menu_Month){
            firstMenuType=Type_Menu_Month;
            tvParkingFirstMoney.setText(String.format("%s元/月",chooseParkingList.get(0).getMenuCost()));
        }else {
            firstMenuType=Type_Menu_Year;
            tvParkingFirstMoney.setText(String.format("%s元/年",chooseParkingList.get(0).getMenuCost()));
        }
        if(chooseParkingList.size()<2){
            tvParkingSecondMoney.setVisibility(View.GONE);
        } else {
            tvParkingSecondMoney.setVisibility(View.VISIBLE);
            tvParkingSecondMoney.setText(String.format("%s元/%s",chooseParkingList.get(1).getMenuCost(),firstMenuType==Type_Menu_Year?"月":"年"));
        }
        setCombo(1);
    }

    /**
     * 设置套餐类型
     * @param combo 选择的套餐 1：第一个 2：第二个
     * 1：选择的购买数量置为1
     * 2：时间默认使用后台返回的时间：非续约返回的应是当天，续约返回的是套餐结束后一天，并清空时间滚轮的位置
     * 3：在后台返回数据错误时，及未给予对应套餐直接退出
     */
    private void setCombo(int combo) {
        this.combo = combo;
        tvParkingCount.setText("1");
        txStartTime.setText(Utils.getStrByLong(curDateLong));
        position=0;
        int addNumber;
        if(chooseParkingList.size()==0)return;
        switch (combo) {
            case 1://选择第一个
                tvParkingFirstMoney.setTextColor(ContextCompat.getColor(this, R.color.font_main));
                tvParkingFirstMoney.setBackgroundResource(R.drawable.red_submit_btn_bg);
                tvParkingSecondMoney.setTextColor(ContextCompat.getColor(this, R.color.font_hint));
                tvParkingSecondMoney.setBackgroundResource(R.drawable.gray_stroke_bg);
                if(firstMenuType==Type_Menu_Month){
                    tvMonthHint.setText("X 自然月");
                    addNumber=1;
                }else {
                    tvMonthHint.setText("X 自然年");
                    addNumber=12;
                }
                endTime=Utils.setEndTime(addNumber,txStartTime.getText().toString());
                tmlParkingEnd.setRightText(endTime);
                chooseId=chooseParkingList.get(0).getId();
                break;
            case 2://选择第二个
                if(chooseParkingList.size()<2)return;
                tvParkingSecondMoney.setTextColor(ContextCompat.getColor(this, R.color.font_main));
                tvParkingSecondMoney.setBackgroundResource(R.drawable.red_submit_btn_bg);
                tvParkingFirstMoney.setTextColor(ContextCompat.getColor(this, R.color.font_hint));
                tvParkingFirstMoney.setBackgroundResource(R.drawable.gray_stroke_bg);
                if(firstMenuType==Type_Menu_Year){
                    tvMonthHint.setText("X 自然月");
                    addNumber=1;
                }else {
                    tvMonthHint.setText("X 自然年");
                    addNumber=12;
                }
                endTime=Utils.setEndTime(addNumber,txStartTime.getText().toString());
                tmlParkingEnd.setRightText(endTime);
                chooseId=chooseParkingList.get(1).getId();
                break;
        }
    }

    @OnClick({R.id.relative_no_data,R.id.tv_parking_underground, R.id.tv_parking_ground, R.id.tv_parking_first_money, R.id.tv_parking_second_money, R.id.btn_parking_decrease, R.id.btn_parking_plus, R.id.iv_info, R.id.tv_next,R.id.relative_start_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_parking_underground:
                if(tvParkingGround.getVisibility()==View.GONE)return;//如果仅该栏目显示，点击无效
                setCarType(Type_Car_Station_Down);
                break;
            case R.id.tv_parking_ground:
                if(tvParkingUnderground.getVisibility()==View.GONE)return;//如果仅该栏目显示，点击无效
                setCarType(Type_Car_Station_Up);
                break;
            case R.id.tv_parking_first_money:
                if(tvParkingSecondMoney.getVisibility()==View.GONE)return;//如果仅该栏目显示，点击无效
                setCombo(1);
                break;
            case R.id.tv_parking_second_money://第二个栏目显示，说明必定显示了第一个栏目
//                if(tvParkingFirstMoney.getVisibility()==View.GONE)return;//如果仅该栏目显示，点击无效
                setCombo(2);
                break;
            case R.id.btn_parking_decrease:
                reduce();
                break;
            case R.id.btn_parking_plus:
                plus();
                break;
            case R.id.relative_start_time:
                if(curDateLong==0)return;
                ParkTimeDialog parkTimeDialog=ParkTimeDialog.getParkTimeDialog(position,curDateLong);
                parkTimeDialog.show(getSupportFragmentManager(),"number");
                break;
            case R.id.iv_info:
                new MaterialDialog.Builder(this)
                        .content(R.string.info_parking)
                        .positiveText(R.string.i_know).show();
                break;
            case R.id.tv_next:
                String carNumber=etParking.getText().toString().trim();
                if(TextUtils.isEmpty(carNumber)){
                    ToastUtil.show("请输入车牌号");
                    return;
                }
                if(carNumber.length()<7){
                    ToastUtil.show("请输入正确的车牌号");
                    return;
                }
                submitParkOrder(carNumber);
                break;
        }
    }

    /**
     * 提交停车申请
     */
    private void submitParkOrder(String carNumber){
        CarPlaceInfo placeInfo=new CarPlaceInfo();
        placeInfo.setBuyNum(tvParkingCount.getText().toString());
        placeInfo.setCarNum(carNumber);
        placeInfo.setCarPlaceRuleId(chooseId);
        placeInfo.setStartTime(txStartTime.getText().toString());
        placeInfo.setEndTime(endTime);
        placeInfo.setIdentity(isPersonPark?0:1);
        placeInfo.setPubobj(UserUtils.isUnLinkCompany()?0:1);
        String placeInfoStr=new Gson().toJson(placeInfo);
        Map<String,String> params=new HashMap<>();
        params.put("placeInfo",placeInfoStr);
        params.put("subId",subId);
        if(!TextUtils.isEmpty(orderId)) params.put("orderId",orderId);
        showLoading();
        enqueue(createCallService(ServiceService.class).carPlaceOrder(params), new RetrofitCallbackListener<ParkPlaceOrderResp>() {
            @Override
            public void onSuccess(Call<ParkPlaceOrderResp> call, ParkPlaceOrderResp result) {
                misLoading();
                if(result.getData()==null||result.getData().getPlaceInfoOrder()==null)return;
                MeetPartOrderSureActivity.startFromPark(ParkingApplyActivity.this,result.getData(), Constants.PARKING_CODE,subId,busId,!isPersonPark);
            }

            @Override
            public void onError(String msg) {
                misLoading();
                ToastUtil.show(msg);
            }
        });
    }

    //增加月
    private void plus() {
        if (combo == 2&&firstMenuType==Type_Menu_Month||combo == 1&&firstMenuType==Type_Menu_Year) {
            return;
        }
        int count = StringUtils.toInt(tvParkingCount.getText());
        if (count < 12) {
            count++;
            tvParkingCount.setText(StringUtils.toString(count));
            endTime=Utils.setEndTime(count,txStartTime.getText().toString());
            tmlParkingEnd.setRightText(endTime);
        }
    }

    //减少月
    private void reduce() {
        if (combo == 2&&firstMenuType==Type_Menu_Month||combo == 1&&firstMenuType==Type_Menu_Year) {
            return;
        }
        int count = StringUtils.toInt(tvParkingCount.getText());
        if (count > 1) {
            count--;
            tvParkingCount.setText(StringUtils.toString(count));
            endTime=Utils.setEndTime(count,txStartTime.getText().toString());
            tmlParkingEnd.setRightText(endTime);
        }
    }

    /**
     * 选择时间回调：年选择时加12个月，月选择时加对应的数目
     * @param showDate 界面展现的字符串
     * @param position 选择的日期position
     */
    @Override
    public void onChooseDate(String showDate, int position) {
        txStartTime.setText(showDate);
        this.position=position;
        int count = StringUtils.toInt(tvParkingCount.getText());
        count=combo==1?count:12;
        endTime=Utils.setEndTime(count,txStartTime.getText().toString());
        tmlParkingEnd.setRightText(endTime);
    }

    /**
     * 由支付成功or申请记录续约进入
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //支付成功回到此界面:注意此处可能有续约进入，需要重置标题，车牌编辑框,开始时间右侧箭头及可点击
        boolean paySuccess = intent.getBooleanExtra("paySuccess", false);
        if(paySuccess){
            etParking.setText("");//车牌号置为空
            etParking.setTextColor(ContextCompat.getColor(this,R.color.font_main));
            etParking.setEnabled(true);

            position=0;//此处请空开始时间的选择位置
            orderId="";//清空订单id
            relative_start_time.setEnabled(true);
            txStartTime.setCompoundDrawablesWithIntrinsicBounds(null,null,ContextCompat.getDrawable(this,R.mipmap.right_arrow),null);

            setBarTitle(false);
            getData();
            return;
        }
        //续约进入:1 车牌号固定，2 套餐根据id去获取，3 开始时间不可更改，4 标题修改，右侧申请记录隐藏
        String orderId=intent.getStringExtra("orderId");
        if(!TextUtils.isEmpty(orderId)){
            etParking.setTextColor(ContextCompat.getColor(this,R.color.font_color_gray));
            etParking.setEnabled(false);

            relative_start_time.setEnabled(false);
            txStartTime.setCompoundDrawables(null,null,null,null);

            this.orderId=orderId;
            getData();

            setBarTitle(true);
        }
    }

    private void setBarTitle(boolean isContinuePark){
        if(isContinuePark){
            StyleUtil.title(this,"停车申请续约");
        }else {
            StyleUtil.titleBackKeyWithRightTextViewListener(this, "停车申请", "申请记录", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Bundle bundle=new Bundle();
                    bundle.putBoolean("isPersonPark",isPersonPark);
                    qStartActivity(ParkHistoryActivity.class,bundle);
                }
            });
        }
    }
}
